<template>
	<el-row :gutter="0">
		<el-col :span="7">
			<div class="container">
				<el-radio-group style="margin-bottom: 5px;" v-model="isCollapse">
					<el-radio-button title="展开菜单" :label="false">
						<el-icon size="24"><zoom-in></zoom-in></el-icon>
					</el-radio-button>
					<el-radio-button title="折叠菜单" :label="true">
						<el-icon size="24"><zoom-out></zoom-out></el-icon>
					</el-radio-button>
				</el-radio-group>
				<el-scrollbar class="margin: 25px 50px 0;" height="600px">
					<el-menu @open="handleOpen" @close="handleClose" :collapse="isCollapse">
						<el-sub-menu index="1">
							<template #title>
								<el-icon><setting></setting></el-icon>
								<el-badge is-dot v-show="sysUnreadMessage !== 0" :value="sysUnreadMessage" type="primary" v-if="isCollapse">
									<div style="margin-top: 25px;"></div>
								</el-badge>
								<span slot="title">
									系统消息
									<el-badge :max="99" v-show="sysUnreadMessage !== 0" :value="sysUnreadMessage" type="primary">
										<div style="margin-top: 45px; margin-left: 15px;"></div>
									</el-badge>
								</span>
							</template>
							<el-menu-item-group title="未读消息">
								<el-menu-item @click="showSysMessageDetail()" index="1-1-1" v-show="sysUnreadMessage != 0">
									<el-badge v-show="sysUnreadMessage !== 0" :value="sysUnreadMessage" type="danger" style="text-align: right;"><div style=""></div></el-badge>
									<div style="margin-left: 30px;">系统通知</div>
								</el-menu-item>
							</el-menu-item-group>
							<el-menu-item-group title="历史消息">
								<el-menu-item @click="showSysMessageDetail()" index="1-2-1" v-show="sysUnreadMessage == 0">
									<el-badge v-show="sysUnreadMessage !== 0" :value="sysUnreadMessage" type="danger" style="text-align: right;"><div style=""></div></el-badge>
									<div style="margin-left: 30px;">系统通知</div>
								</el-menu-item>
							</el-menu-item-group>
						</el-sub-menu>
						<el-sub-menu index="2">
							<template #title>
								<el-icon><user></user></el-icon>
								<el-badge is-dot v-show="userUnreadMessage !== 0" :value="userUnreadMessage" type="primary" v-if="isCollapse">
									<div style="margin-top: 25px;"></div>
								</el-badge>
								<span slot="title">
									用户消息
									<el-badge :max="99" v-show="userUnreadMessage !== 0" :value="userUnreadMessage" type="primary">
										<div style="margin-top: 45px; margin-left: 15px;"></div>
									</el-badge>
								</span>
							</template>
							<el-menu-item-group title="未读消息">
								<!-- :index="`2-${index + 1}`" -->
								<el-menu-item
									v-for="(item, index) in usersDetail"
									:key="index"
									:index="`2-1-${index + 1}`"
									@click="showMessageDetail(index)"
									v-show="item.unreadCount != 0"
								>
									<el-badge v-show="item.unreadCount !== 0" :value="item.unreadCount" type="danger" style="text-align: right;"><div style=""></div></el-badge>
									<div style="margin-left: 30px;">用户名：{{ item.user.username }}</div>
								</el-menu-item>
							</el-menu-item-group>
							<el-menu-item-group title="历史消息">
								<el-menu-item
									v-for="(item, index) in usersDetail"
									:key="index"
									:index="`2-2-${index + 1}`"
									@click="showMessageDetail(index)"
									v-show="item.unreadCount == 0"
								>
									<div style="margin-left: 30px;">用户名：{{ item.user.username }}</div>
								</el-menu-item>
							</el-menu-item-group>
						</el-sub-menu>
					</el-menu>
				</el-scrollbar>
			</div>
		</el-col>

		<el-col :span="17">
			<div class="message-box">
				<!-- <b style="color:  rgba(255, 255, 255); display: flex;justify-content: center;align-items: center;height: 100%; ">暂无消息</b> -->
				<div class="chat-room">
					<div class="chat-header">
						<b v-if="isSystem == true">系统通知</b>
						<b v-else-if="talkingUser">与用户{{ talkingUser.username }}的对话</b>
						<b v-else>暂无会话</b>
					</div>

					<div class="chat-body">
						<el-container>
							<el-main class="chat-main" style="padding: 5px;">
								<div class="chat-messages">
									<div class="chat-message" v-for="message in messages" :key="message.id" :class="{ 'is-me': message.isMe, 'is-sys': message.isSys }">
										<div class="message-content">{{ message.content }}</div>
										<div class="message-date">发送时间：{{ message.createDate }}</div>
									</div>
								</div>
							</el-main>
						</el-container>
					</div>

					<div class="chat-footer">
						<el-form :model="form" class="chat-form">
							<el-form-item @keyup.enter.native="sendMessage">
								<el-input
									:disabled="isSystem"
									style="margin-left: 15px; width: 90%; margin-top: 20px;margin-bottom: 10px; "
									type="textarea"
									:rows="3"
									v-model="form.message"
									:placeholder="isSystem ? '您正在与系统会话中，无法发送消息' : '输入您要发送的信息'"
								></el-input>
							</el-form-item>
							<el-form-item><el-button :disabled="isSystem" style="margin-right: 15px;" type="primary" @click="sendMessage">发送消息</el-button></el-form-item>
						</el-form>
					</div>
				</div>
			</div>
		</el-col>
	</el-row>
</template>

<script>
import { ElMessage } from 'element-plus';
import { getMyConversation, sendMessage, setRead } from '@/api/conversation';
import { getUserDetails } from '@/api/user';
import { log } from 'util';

export default {
	data() {
		return {
			isCollapse: false,

			userUnreadMessage: 0,
			sysUnreadMessage: 0,
			messageCenter: [],

			isSystem: false,

			messages: [],

			usersDetail: [],
			userMessage: [],
			systemMessage: [],

			loginUser: '',
			talkingUser: '',

			form: {
				message: ''
			}
		};
	},
	methods: {
		handleOpen(key, keyPath) {
			// console.log(key, keyPath);
		},
		handleClose(key, keyPath) {
			// console.log(key, keyPath);
		},
		sendMessage(event) {
			if (event.keyCode === 13 && (event.ctrlKey || event.shiftKey)) {
				return;
			}
			if (!this.talkingUser) {
				ElMessage.error('消息无法发送，清先选择发送的用户');
				this.form.message = '';
				return;
			}
			if (!this.form.message.trim()) {
				ElMessage.error('无法发送空消息');
				return;
			}
			const newMessage = {
				id: this.messages.length + 1,
				content: this.form.message,
				createDate: new Date().toLocaleString('zh-CN', { hour12: false }),
				isMe: true
			};

			const dataPack = {
				toUser: this.talkingUser,
				content: this.form.message
			};
			sendMessage(dataPack);
			this.messages.push(newMessage);
			this.form.message = '';
			this.$nextTick(() => {
				setTimeout(() => {
					this.scrollToBottom();
				}, 0);
			});
		},
		scrollToBottom() {
			//使用js滑动滚动条需要判断滚动条处于哪个容器内
			//滚动的是messages，但是滚动条实际上在main容器里
			const elMessage = this.$el.querySelector('.chat-messages');
			const elMain = this.$el.querySelector('.chat-main');

			this.$nextTick(() => {
				setTimeout(() => {
					elMain.scrollTop = elMessage.scrollHeight;
				}, 20);
			});
		},
		showMessageDetail(index) {
			const fromId = this.usersDetail[index].user.id;
			this.isSystem = false;
			// console.log(fromId);
			// console.log(this.loginUser.id);
			if (this.talkingUser.id != fromId) {
				this.messages = [];
			}

			for (let item of this.usersDetail) {
				if (item.user.id == fromId) {
					this.talkingUser = item.user;
					item.unreadCount = 0;
				} else {
					//后台获取用户信息后返回
				}
			}

			var messages = this.userMessage[index];

			for (let item of messages) {
				if (item.fromId === this.loginUser.id) {
					Object.defineProperty(item, 'isMe', {
						value: true,
						writable: true,
						configurable: true,
						enumerable: true
					});
					// item.push({ isMe: true });
				}
				this.messages.push(item);
			}

			//this.scrollToBottom();
			//设置会话已读状态
			const param = {
				conversationId: fromId + '_' + this.loginUser.id
			};

			setRead(param);
			// console.log(this.messages);
		},
		showSysMessageDetail() {
			const fromId = 0;
			// console.log(fromId);
			// console.log(this.loginUser.id);
			//如果这消息不是这个用户发送的，则清空消息列表
			if (this.talkingUser.id != fromId) {
				this.isSystem = false;
				this.messages = [];
			}
			for (let sysItem of this.systemMessage) {
				if (sysItem.fromId === 0) {
					Object.defineProperty(sysItem, 'isSys', {
						value: true,
						writable: true,
						configurable: true,
						enumerable: true
					});
				}
				this.messages.push(sysItem);
			}

			this.isSystem = true;
			//this.scrollToBottom();
			//设置会话已读状态
			const param = {
				conversationId: fromId + '_' + this.loginUser.id
			};
			this.sysUnreadMessage = 0;

			setRead(param);
		},
		getMyConversations() {
			getMyConversation().then(resp => {
				this.messageCenter = resp.data;
				this.userMessage = this.messageCenter.userMessage;
				this.systemMessage = this.messageCenter.systemMessage;
				var unreadAndUser = [];
				var unreadCount = 0;

				for (let item of this.userMessage) {
					//增加判断未读消息数量
					// console.log(item);
					var unreadCount = 0;
					var talkId = '';
					for (let message of item) {
						if (message.toId == this.loginUser.id && message.status == 0) {
							unreadCount++;
						} else {
							unreadCount = 0;
						}
					}
					//判断消息发送者
					if (item[0].fromId != this.loginUser.id) {
						talkId = item[0].fromId;
					} else {
						talkId = item[0].toId;
					}
					unreadAndUser.push({
						userId: talkId,
						unreadCount: unreadCount
					});
					//总未读数
					this.userUnreadMessage += unreadCount;
				}

				for (let item of this.systemMessage) {
					console.log(item);
					var unreadCount = 0;
					var talkId = '';
					//判断未读消息

					if (item.fromId == 0 && item.status == 0) {
						unreadCount++;
					} else {
						unreadCount = 0;
					}

					talkId = 0;
					//总未读数
					this.sysUnreadMessage += unreadCount;
				}

				var userIds = [];
				for (let user of unreadAndUser) {
					userIds.push({ id: user.userId });
				}

				getUserDetails(userIds).then(resp => {
					for (let item of resp.rows) {
						for (let item1 of unreadAndUser) {
							if (item1.userId === item.id) {
								const data = { user: item, unreadCount: item1.unreadCount };
								this.usersDetail.push(data);
							}
						}
					}
				});
			});
		}
	},
	mounted() {
		this.loginUser = JSON.parse(sessionStorage.getItem('user'));
		this.getMyConversations();

		this.$nextTick(() => {
			this.scrollToBottom();
		});
	}
};
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
	width: 200px;
	min-height: 400px;
}
.container {
	width: 65%;
	display: inline-block;
	border: 1px solid #ccc;
	padding: 10px;
	background-color: rgba(255, 255, 255, 0.7);
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
	margin: 25px 30px 0;
	font-size: 24px;
	height: 650px;
}
.message-box {
	flex: 0 0 auto;
	border: 1px solid #ccc;
	padding: 10px;
	background-color: rgba(108, 108, 108, 0.7);
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
	margin: 25px;
	font-size: 16px;
	height: 650px;
}
.chat-room {
	display: flex;
	flex-direction: column;
	height: calc(100% - 10px); /* 减去 message-box 和 chat-footer 的高度 */
	position: relative; /* 添加 position 属性 */
}
.chat-header {
	max-height: 30px;
	background-color: rgb(96, 181, 255);
	color: #fff;
	text-align: center;
	padding: 10px;
}
.chat-body {
	max-height: 65%;
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 20px;
}

.chat-messages {
	height: 400px;
	margin-bottom: 20px;
}
.chat-message {
	display: flex;
	margin-bottom: 20px;
	border-radius: 10px;
	position: relative;
}
.chat-message.is-me {
	flex-direction: row-reverse;
}
.is-sys div.message-content {
	white-space: pre-wrap;
	max-width: 70%;
	word-break: break-all;
	text-align: left;
	background-color: #6cf2ee;
	color: #383838;
	border-radius: 20px;
	padding: 5px 10px;
	margin: 10px 0;
	font-size: 18px;
}
.is-sys div.message-content:hover {
	background-color: #f23f42;
	color: #ddd94c;
}
.message-content {
	white-space: pre-wrap;
	padding: 10px;
	background-color: #f2e7da;
	border-radius: 10px;
	max-width: 70%;
	word-break: break-all;
	text-align: left;
}
.message-date {
	position: absolute;
	top: calc(100% - 1%);
	font-size: 10px;
	opacity: 0;
}
.message-date:hover {
	color: #fff;
	opacity: 1;
}
.chat-message.chat-message.is-me .message-content {
	background-color: #1affce;
}

.chat-footer {
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: #f0f0f0;
	border-top: 1px solid #ebebeb;
	z-index: 1;
}

.chat-form {
	display: flex;
	align-items: center;
}

.chat-form .el-form-item:first-child {
	margin-right: 10px;
	flex: 1;
}
</style>
